<?php
/**
 * Author: lf
 * Blog: https://blog.feehi.com
 * Email: job@feehi.com
 * Created at: 2017-03-15 21:16
 */

namespace backend\controllers;

use common\services\InformationService;
use Yii;
use yii\data\ArrayDataProvider;
use common\models\Information;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class InformationController extends AdminBaseController
{
    /**
     * 信息列表页
     * @return string
     */
    public function actionIndex()
    {
        $model = Information::find();
        $search = Yii::$app->request->post() ?: [
            'name' => '',
            'mobile' => '',
            'start_date' => '',
            'end_date' => '',
        ];
        $sale_id = Yii::$app->session->get(Yii::$app->session->name)['id'];
        $map = [];
        if ($sale_id != 1) {
            $map[] = ['=', 'sale_id', $sale_id];
        }
        // 带搜索条件
        if ($search) {
            unset($search[Yii::$app->request->csrfParam]);
            // 姓名
            if ($name = ArrayHelper::getValue($search, 'name')) {
                $map[] = ['like', 'name', $name];
            }
            // 手机
            if ($mobile = ArrayHelper::getValue($search, 'mobile')) {
                $map[] = ['like', 'mobile', $mobile];
            }
            // 提交日期
            $start_date = strtotime(ArrayHelper::getValue($search, 'start_date'));
            $end_date = strtotime(ArrayHelper::getValue($search, 'end_date'));
            if ($start_date || $end_date) {
                $map[] = ['between', 'add_time', $start_date ?: 0, $end_date ?: time()];
            }
        }
        if ($map) {
            array_unshift($map, 'and');
            $model = $model->where($map);
        }
        // 得到文章的总数（但是还没有从数据库取数据）
        $count = $model->count();

        // 使用总数来创建一个分页对象
        $pagination = new Pagination(['totalCount' => $count]);

        // 使用分页对象来填充 limit 子句并取得文章数据
        $list = $model->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        return $this->render('index', ['list' => $list, 'page' => $pagination, 'search' => $search]);
    }

    /**
     * 导出数据
     */
    public function actionExport()
    {
        $search = Yii::$app->request->get();
        $map = [];
        // 带搜索条件
        if ($search) {
            unset($search[Yii::$app->request->csrfParam]);
            // 姓名
            if ($name = ArrayHelper::getValue($search, 'name')) {
                $map[] = ['like', 'name', $name];
            }
            // 手机
            if ($mobile = ArrayHelper::getValue($search, 'mobile')) {
                $map[] = ['like', 'mobile', $mobile];
            }
            // 提交日期
            $start_date = strtotime(ArrayHelper::getValue($search, 'start_date'));
            $end_date = strtotime(ArrayHelper::getValue($search, 'end_date'));
            if ($start_date || $end_date) {
                $map[] = ['between', 'add_time', $start_date ?: 0, $end_date ?: time()];
            }
        }
        if ($map) {
            array_unshift($map, 'and');
        }
        $service = new InformationService();
        $result = $service->export($map);
        // echo $result;die;
        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . time() . '.csv');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo iconv('UTF-8', 'GBK//IGNORE', $result);
        die;
    }

    /**
     * 查看页面
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id') ?: 0;
        $info = Information::findOne(['id' => $id]);
        if (!$info) {
            throw new NotFoundHttpException('信息不存在');
        }
        return $this->render('edit', ['info' => $info]);
    }

    /**
     * 删除操作
     * @return array|string
     */
    public function actionDel()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $id = Yii::$app->request->get('id') ?: 0;
        if (Information::deleteAll(['id' => $id]) !== false) {
            return ['status' => 200, 'message' => '删除成功'];
        }
        return ['status' => 400, 'message' => '删除失败'];
    }

}